package com.alipay.rebate.shop.service.admin.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.rebate.shop.constants.StatusCode;
import com.alipay.rebate.shop.core.ResultGenerator;
import com.alipay.rebate.shop.dao.mapper.AppSettingsMapper;
import com.alipay.rebate.shop.exceptoin.BusinessException;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.pojo.user.admin.UpdateUserRequest;
import com.alipay.rebate.shop.pojo.user.admin.UserListResponse;
import com.alipay.rebate.shop.pojo.user.admin.UserPageRequest;
import com.alipay.rebate.shop.pojo.user.customer.UpdateUserStatusReq;
import com.alipay.rebate.shop.pojo.user.customer.UserDto;
import com.alipay.rebate.shop.service.admin.AdminCustomerUserService;
import com.alipay.rebate.shop.service.common.AbstractUserService;
import com.alipay.rebate.shop.utils.EncryptUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class AdminCustomerUserServiceImpl extends AbstractUserService implements AdminCustomerUserService {

  private Logger logger = LoggerFactory.getLogger(AdminCustomerUserServiceImpl.class);
  @Resource
  AppSettingsMapper appSettingsMapper;

  @Override
  public PageInfo<UserListResponse> searchUserByCondition(
      UserPageRequest userPageRequest) {
    logger.debug("pageSize is: {}", userPageRequest.getPageSize());
    logger.debug("pageNo is: {}", userPageRequest.getPageNo());

    PageHelper.startPage(userPageRequest.getPageNo(), userPageRequest.getPageSize());

    List<UserListResponse> page = userMapper.selectUserByCondition(userPageRequest);
    logger.debug("page is : {}", page);
    PageInfo<UserListResponse> pageInfo = new PageInfo<>(page);
    logger.debug("pageInfo is:{}", pageInfo);
    return pageInfo;
  }

  @Override
  public UserDto getUserDtoInfoForAdminLogin(String phone) {
    return userMapper.selectUserDtoInfoForAdminLogin(phone);
  }

//  @Transactional
//  @Override
//  public ResponseResult<UserPersonalCenterResponse> adminLogin(
//      UserDto loginInfo,
//      HttpServletResponse response,
//      Subject subject)
//  {
//    ResponseResult<UserPersonalCenterResponse> responseResult = new ResponseResult<>();
//
//    // 生成WeixinToken
//    AdminToken adminToken = new AdminToken();
//    adminToken.setUsername(loginInfo.getAccount());
//    adminToken.setPassword(loginInfo.getPassword());
//    logger.debug("Login AdminAccountToken is : {}", adminToken);
//    // 登陆
//    subject.login(adminToken);
//    logger.debug("Shiro Login success");
//    // 生成token并且设置到header中
//    generateTokenAndSetIngoHeader(response, subject, UserContant.PC_LOGIN_TYPE);
//    return responseResult;
//  }

  @Override
  public int selectTotalCountByCondition(Map<String, Object> map) {
    return userMapper.selectTotalCountByCondition(map);
  }

  @Override
  public void cancelTaobaoAuth(Long id) {
    userMapper.setTaobaoAuthRelationIdToNullById(id);
  }

  /**
   * 更新用户信息
   * @param updateUserRequest
   * @return
   */
  @Override
  public int updateUserById(UpdateUserRequest updateUserRequest) {

    logger.debug("Receive id and UpdateUserRequest body from request : {}",updateUserRequest);

    String password = updateUserRequest.getPassword();
    logger.debug("password is : {}",password);

    User user = new User();
    user.setUserId(updateUserRequest.getUserId());
    user.setUserNickName(updateUserRequest.getUserNickName());
    user.setRealName(updateUserRequest.getRealName());
    user.setAlipayAccount(updateUserRequest.getAlipayAccount());
    logger.debug("realName is : {}",user.getRealName());
    logger.debug("AlipayAccount is : {}",user.getAlipayAccount());
    if (StringUtils.isEmpty(user.getRealName()) || StringUtils.isEmpty(user.getAlipayAccount())){
      userMapper.updateUserAlipayAccount(user.getUserId(),user.getRealName(),user.getAlipayAccount());
    }
    Optional.ofNullable(updateUserRequest.getUserRegisterTime()).ifPresent(registerTime -> {
      user.setUserRegisterTime(new Date(updateUserRequest.getUserRegisterTime()));
    });
    user.setUserRegisterIp(updateUserRequest.getUserRegisterIp());
    user.setUserAmount(updateUserRequest.getUserAmount());
    user.setUserIntgeralTreasure(updateUserRequest.getUserIntgeralTreasure());
    user.setUserIntgeral(updateUserRequest.getUserIntgeral());
    user.setPhone(updateUserRequest.getPhone());
    user.setParentUserId(updateUserRequest.getParentUserId());
    if (!StringUtils.isEmpty(updateUserRequest.getUserPassword())) {
      user.setUserPassword(EncryptUtil.encryptPassword(updateUserRequest.getUserPassword()));
    }
    user.setUserStatus(updateUserRequest.getUserStatus());
    user.setUserGradeId(updateUserRequest.getUserGradeId());

    int result = 0;
    if(password==null) {
      result = userMapper.updateUser(user);

    }

    if (password != null){
      String pwd = EncryptUtil.encryptPassword(password);
      String selectPassword = appSettingsMapper.selectPassword();
      logger.debug("selectPassword is : {}", selectPassword);
      if (selectPassword.equals(pwd)){
        result = userMapper.updateUser(user);
      }else{
        throw new RuntimeException("校验密码输入错误");
      }
    }

    return result;
  }

  @Override
  public int updateUserStatus(UpdateUserStatusReq req) {
    User user = new User();
    user.setUserId(req.getUserId());
    user.setUserStatus(req.getStatus());
    if (req.getStatus() == 0){
      if (StringUtils.isEmpty(req.getRemarks()))
      throw new BusinessException("拉黑备注信息不能为空", StatusCode.INTERNAL_ERROR);
    }
    if (req.getStatus() == 0){
      user.setRemarks(req.getRemarks());
    }
    int result = userMapper.updateUser(user);
    return result;
  }
}
